package cn.water.luban.demo.gateway.error;

import cn.water.luban.demo.gateway.ex.GatewayException;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;

@Component
@Order(-1)//保证自定义的错误处理器在网关的错误处理之后执行
public class MyErrorHandler implements ErrorWebExceptionHandler {
    /**
     * 当前请求的封装包含请求和响应
     * @param exchange
     * @param ex
     * @return
     */
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        String message;
        if(ex instanceof GatewayException){
            message = ex.getMessage();
        }else{
            message="网关异常,请检查";
        }
        //响应数据
        ServerHttpResponse response = exchange.getResponse();
        byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
        DataBuffer wrap = dataBufferFactory.wrap(bytes);
        return response.writeWith(Mono.fromSupplier(new Supplier<DataBuffer>() {
            @Override
            public DataBuffer get() {
                return wrap;
            }
        }));
    }
}
